<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="../include/tag.jsp" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${article == null ? '发布' : '编辑'}文章</title>
    <%@include file="../include/commonFile.jsp" %>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_act.css">
</head>
<body>
<!--头部-->
<%@include file="../include/header.jsp" %>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp" %>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/article/article/save.do">
                    <input type="hidden" name="applyId" value="${subjectApply.id}"/>
                    <input type="hidden" name="subjectId" value="${subjectId}"/>
                    <input type="hidden" name="channelId" value="${channel.id}"/>
                    <input type="hidden" name="id" value="${article.id}"/>
                    <div class="layui-form-item">
                        <label class="layui-form-label">标题<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" maxlength="35" name="title" lay-verify="title" autocomplete="off"
                                   class="layui-input margin-right" value="${article.title}"
                                   style="width: 50%; ">
                            <div class="layui-form-mid layui-word-aux">文章标题，最多35字符</div>
                            <div class="cl"></div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">简介</label>
                        <div class="layui-input-block">
                            <input type="text" maxlength="50" name="subTitle" autocomplete="off"
                                   class="layui-input margin-right" value="${article.subTitle}"
                                   style="width: 50%; ">
                            <div class="layui-form-mid layui-word-aux">文章简介，最多50字符</div>
                            <div class="cl"></div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">封面图<span class="f-verify-red">*</span></label>
                        <div class="cover-content">
                            <input type="hidden" name="pic" id="pic" lay-verify="pic" value="${article.pic}"/>
                            <c:if test="${article == null || empty article.pic}">
                                <span id="cover-img" class="cover-img"
                                      style="background-image:url(${ctx}/image/posterImg.png)"></span>
                            </c:if>
                            <c:if test="${article != null && not empty article.pic}">
                                <span id="cover-img" class="cover-img"
                                      style="background-image:url('${article.pic}')"></span>
                            </c:if>
                            <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加封面图</a>
                            <div class="form-word-aux">建议尺寸：800x450</div>
                        </div>
                    </div>
                    <c:if test="${applyType == 'channel'}">
                        <c:if test="${empty channel.id}">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">文章类别</label>
                                    <div class="layui-input-inline">
                                        <select name="channel.id">
                                            <option value="">请选择栏目下文章类别</option>
                                            <c:forEach var="channel" items="${channels}">
                                                <option value="${channel.id}" ${article.channel.id == channel.id ? 'selected="selected"' : ""}>${channel.name}</option>
                                            </c:forEach>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </c:if>
                        <c:if test="${not empty channel.id}">
                            <div class="layui-form-item">
                                <label class="layui-form-label">文章分类</label>
                                <div class="layui-input-block">
                                    <input type="text" style="width: 20%" class="layui-input" value="${channel.name}" readonly="readonly" />
                                </div>
                            </div>
                        </c:if>
                    </c:if>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">文章类型</label>
                            <div class="layui-input-inline">
                                <select name="articleType">
                                    <option value="">请选择类型</option>
                                    <c:forEach var="type" items="${types}">
                                        <option value="${type.value}" ${article.articleType == type.value ? 'selected="selected"' : ""}>${type.label}</option>
                                    </c:forEach>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">是否热门</label>
                            <div class="layui-input-inline">
                                <input type="radio" name="isHot" value="1"
                                       title="是" ${article != null && article.isHot == '1' ? 'checked="checked"' : ''} />
                                <input type="radio" name="isHot" value="0"
                                       title="否" ${article == null || article.isHot == '0' ? 'checked="checked"' : ''} />
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">阅读数</label>
                            <div class="layui-input-inline">
                                <input type="text" name="readNum" lay-verify="readNum" autocomplete="off" class="layui-input" value="${article.readNum}">
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">文章内容来源<span class="f-verify-red">*</span></label>
                            <div class="layui-input-block">
                                <input type="radio" name="type" lay-filter="type" lay-verify="type" value="local"
                                       title="本地发布"
                                ${article == null || article.type == 'local' ? 'checked="checked"' : ''}> <input
                                    type="radio" name="type"
                                    lay-filter="type" lay-verify="type" value="out" title="指向外部链接"
                            ${article != null && article.type == 'out' ? 'checked="checked"' : ''}>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item"
                         id="urlDiv" ${article != null && article.type == "out" ? '' : 'style="display: none;"'}>
                        <label class="layui-form-label">链接<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" name="url" class="layui-input" value="${article.url}" lay-verify="url"
                                   id="url"
                                   placeholder="以http://开头"/>
                        </div>
                    </div>
                    <div class="layui-form-item"
                         id="localDiv" ${article == null || article.type == "local" ? '' : 'style="display: none;"'}>
                        <label class="layui-form-label">内容<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <script id="ueditor1" type="text/plain"></script>
                            <div style="display: none" id="contentView">${article.content}</div>
                            <input type="hidden" name="content" id="content" lay-verify="content"
                                   data-link-ue="ueditor1"/>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                            <a href="${ctx}/subject/apply/applyList.do?subjectId=${subject.id}"
                               class="layui-btn layui-btn-primary">取消</a>
                        </div>
                    </div>
                </form>
            </div>
        </div><!--底部-->
        <%@include file="../include/footer.jsp" %>
    </section>
</div>

<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.config.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/ueditor.all.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadCI.js"></script>
<script type="text/javascript" src="${ctxStatic}/UEditor/myplugin/uploadVideo.js"></script>
<!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
<script type="text/javascript" src="${ctxStatic}/UEditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="${ctx}/script/common/form_cache.js"></script>
<script>
    txz.initHeader({
        nav: [{
            name: '手机官网',
            href: '${ctx}/subject/apply/applyList.do?subjectId=${subject.id}'
        }, {
            name: '${subject.name}'
        }, {
            name: '${subjectApply.name}'
        }, {
            name: '${article == null ? '发布' : '编辑'}文章',
            curr: true
        }],
        btns: [{
            type: 'back'
        }]
    });
    var ue = UE.getEditor('ueditor1', {
        initialFrameHeight: 500,//设置编辑器高度
        scaleEnabled: true
    }), form, formcache;

    $(function () {
        layui.use(['form'], function () {
            form = layui.form, laydate = layui.laydate;

            var typeRadioValue = null;

            form.on('radio(type)', function (data) {
                typeRadioValue = data.value;
                toggleRadioType(typeRadioValue);
            });

            //自定义验证规则
            form.verify({
                title: function (value) {
                    if (value == "") {
                        return '请填写文章标题';
                    }
                },
                pic: function (value) {
                    if (value == "") {
                        return "请上传文章封面图";
                    }
                },
                articleType: function (value) {
                    if (value == "") {
                        return "请选择文章类型";
                    }
                },
                url: function (value) {
                    if (typeRadioValue == null) {
                        var type = $("[name=type]:checked").val();
                        if (type == "url") {
                            if (value == "") {
                                return "请填写外部链接";
                            }
                        }
                    } else {
                        if (typeRadioValue == "out") {
                            if (value == "") {
                                return "请填写外部链接";
                            }
                        }
                    }
                },
                content: function (value) {
                    $("#contentView").html(ue.getContent());
                    var content = $("#contentView").html();
                    if (typeRadioValue == null) {
                        var type = $("[name=type]:checked").val();
                        if (type == "local") {
                            if (content == "") {
                                return "请填写文章内容";
                            }
                        }
                    } else {
                        if (typeRadioValue == "local") {
                            if (content == "") {
                                return "请填写文章内容";
                            }
                        }
                    }
                }
            });

            //监听提交
            form.on('submit', function (data) {
                txz.submitObject(data.elem, function (callBack) {
                    var formData = getFormData();
                    var action = $("#myForm").attr("action");
                    txz.ajaxRequest({
                        method: 'post',
                        url: action,
                        saveCache: true,
                        cacheObj: formcache,
                        params: formData,
                        callBack: function (res) {
                            typeof callBack === 'function' && callBack();
                            if (res.success) {
                                util.layerMsgSuccess("提交成功", function () {
                                    if (res.data != undefined) {
                                        location.href = "${ctx}/subject/apply/applyList.do?subjectId=" + res.data.subjectId + "&applyId=" + res.data.applyId;
                                    } else {
                                        location.href = "${ctx}/article/article/publishList.do";
                                    }
                                })
                            } else {
                                util.layerMsgError("提交失败")
                            }
                        }
                    });
                }, '${article.id}')
                return false;
            });

            form.render('radio');
        });
        ue.addListener('ready', function () {
            this.setContent($("#contentView").html());
            //等待ueditor加载完后加载缓存
            if (!'${article.id}') {
                formcache = new fCache({
                    fCacheKey: 'form_cache_article',//暂存的key
                    cacheCallback: loadCacheData,//获取到缓存后加载的方法
                    getFormData: getFormData
                }).init();
            }
        });

        ue.addListener('blur', function () {
            $("#contentView").html(ue.getContent());
        });

        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x450',
                type: '<%=TargetType.ACTIVITY.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
        txz.saveStatus = false;
    })

    function toggleRadioType(typeRadioValue) {
        if (typeRadioValue == "out") {
            $("#urlDiv").show();
            $("#localDiv").hide();
        } else if (typeRadioValue == "local") {
            $("#urlDiv").hide();
            $("#localDiv").show();
        }
    }

    function getFormData() {
        $("#content").val(ue.getContent().replace(/&quot;/gi, ""));
        return util.serializeForm($('#myForm').serializeArray());
    }

    //此方法用于加载缓存数据
    function loadCacheData(cacheData) {
        //加载封面图
        if (cacheData['pic']) {
            $('#cover-img').css('background-image', 'url(' + cacheData['pic'] + ')');
        }
        //文章内容来源
        if (cacheData['type']) {
            toggleRadioType(cacheData['type']);
        }
        form.render();
    }

    // 文本编辑器图片上传
    function uEditorUploadCI(editor) {
        txz.openSelImg({
            min: 1,
            type: '<%=TargetType.ARTICLE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }

    function uEditorUploadCIVideo(editor) {
        txz.openSelVideo({
            min: 1,
            type: '<%=TargetType.ARTICLE.getCode()%>',
            cb: function (imgs) {
                if (imgs.length) {
                    for (var i = 0, item; i < imgs.length; i++) {
                        item = imgs[i];
                        editor.focus();
                        editor.execCommand('inserthtml', item.htmlStr);
                    }
                }
            }
        })
    }
</script>
</body>
</html>